package com.xh.load.service;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * 图片上传Service
 * @author DWQin
 *
 */
@Service
public class UploadService {

	/**
	 * 图片上传
	 * @param file（上传的文件）
	 * @param uploadPath（图片保存文件夹）
	 * @param realUploadPath（图片保存完整路径）
	 * @return
	 */
    public String uploadImage(CommonsMultipartFile file, String uploadPath, String realUploadPath) {
        InputStream is = null ;
        OutputStream os = null ;
        try {
            is = file.getInputStream() ;
            String des = realUploadPath + "\\" + file.getOriginalFilename() ;
            os = new FileOutputStream(des) ;
            byte[] buffer = new byte[1024] ;
            int len = 0 ;
            while((len=is.read(buffer))>0) {
                os.write(buffer);
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(is!=null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return uploadPath + "/" + file.getOriginalFilename() ;
    }
    
    public static final int WIDTH = 400;
	public static final int HEIGHT = 400;
	/**
	 * 图片上传并处理
	 * @param file（图片文件）
	 * @param uploadPath（图片保存文件夹）
	 * @param realUploadPath（图片保存完整路径）
	 * @return
	 */
	public String uploadThum4Image(CommonsMultipartFile file, String uploadPath, String realUploadPath) {
		try {
			String des = realUploadPath + "/thum_" + file.getOriginalFilename();
			Thumbnails.of(file.getInputStream())	//文件流
					  .size(WIDTH, HEIGHT)			//宽高设置
					  .toFile(des);					//输出
		} catch (Exception e) {
			e.printStackTrace();
			return "上传图片错误！";
		}
		return uploadPath + "/thum_" + file.getOriginalFilename();
	}
	
	
	
}